<template>
  <div class="login_container">
    <!-- <img
      src="@/assets/images/login_containerback.png"
      class="login_containerback"
    /> -->
    <!-- <div class="login_title">
      <div class="l">学生端</div>
      <span>管理端</span> 
     <img src="@/assets/images/logotitle.png" alt="" /> 
    </div> -->
    <img
      src="@/assets/images/login1.png"
      alt=""
      class="login_containerback"
      v-if="loding1"
    />
    <img
      src="@/assets/images/login2.png"
      alt=""
      class="login_containerback"
      v-if="loding2"
    />
    <img
      src="@/assets/images/dl.png"
      alt=""
      class="login_gl"
      v-if="!loding1 && !loding2"
    />
    <div class="djbox" v-if="timeLeft != 0" @click="tgfn"
      >{{ timeLeft }}s 跳过
    </div>
    <div
      class="login_form"
      v-if="!loding1 && !loding2"
      :style="{ top: topfalg ? '' : '0px' }"
    >
      <!-- <div class="login_formtitle"> 登录 </div> -->
      <div class="login_formcont">
        <a-form
          ref="loginForm"
          :rules="loginRules"
          :model="userInfo"
          layout="vertical"
        >
          <a-form-item field="username" hide-label>
            <a-input
              v-model="userInfo.username"
              size="large"
              placeholder="请输入用户名"
            >
              <template #prefix>
                <icon-user />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item field="password" hide-label>
            <a-input-password
              v-model="userInfo.password"
              @press-enter="handleCheck"
              size="large"
              placeholder="请输入密码"
              allow-clear
            >
              <template #prefix>
                <icon-lock />
              </template>
            </a-input-password>
          </a-form-item>
          <div class="jzmm">
            <a-checkbox
              checked="rememberPassword"
              :model-value="loginConfig.rememberPassword"
              @change="setRememberPassword as any"
            >
              记住密码
            </a-checkbox>
          </div>
          <div class="loginbott" :loading="loading" @click="handleCheck"
            >登录</div
          >
        </a-form>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, onBeforeMount, onUnmounted, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useStorage } from '@vueuse/core';
  import { useUserStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import { login, tylogin } from '@/api/user';
  const mediaQuery = ref(window.matchMedia('(orientation: landscape)'));
  const topfalg = ref(mediaQuery.value.matches);

  const handleOrientationChange = (event) => {
    console.log(event.matches ? '横屏' : '竖屏');
    topfalg.value = !event.matches;
  };

  // 监听屏幕方向变化
  mediaQuery.value.addEventListener('change', handleOrientationChange);

  // 组件挂载时手动触发一次，确保初始状态
  onMounted(() => {
    handleOrientationChange(mediaQuery.value);
  });

  // 组件销毁时移除监听器
  onUnmounted(() => {
    mediaQuery.value.removeEventListener('change', handleOrientationChange);
  });

  const loding1 = ref(false);
  const loding2 = ref(true);
  const timeLeft = ref(3); // 设置倒计时的初始时间
  const loading1fn = () => {
    setTimeout(() => {
      loding1.value = false;
      loding2.value = true;
      loading2fn();
    }, 2000);
  };
  let timer;
  const loading2fn = () => {
    setTimeout(() => {
      loding2.value = false;
    }, 3000);
    timer = setInterval(() => {
      if (timeLeft.value > 0) {
        timeLeft.value--;
      } else {
        clearInterval(timer); // 清除定时器
      }
    }, 1000);
  };
  loading2fn();
  const tgfn = () => {
    clearInterval(timer);
    timeLeft.value = 0;
    loding2.value = false;
  };
  // 页面创建的时候进行请求
  let currentUrl = ref('');
  onBeforeMount(() => {
    currentUrl.value = window.location.href;

    // 提取查询参数部分（从问号后面开始）
    const queryString = currentUrl.value.split('?')[1];

    if (!queryString) {
      return;
    }
    // 将查询参数按 '&' 分割成数组
    const queryParamsArray = queryString.split('&');
    // 遍历数组查找需要的参数值
    let studentNo: string | null = null;
    let studentName = null;
    queryParamsArray.forEach((param) => {
      const [key, value] = param.split('=');
      if (key === 'user_name') {
        studentNo = value;
      } else if (key === 'nick_name') {
        studentName = decodeURIComponent(value);
      }
    });
    // 获取到数据后去请求
    if (studentNo && studentName) {
      tylogin({
        studentNo: studentNo,
        studentName: studentName,
      }).then((res: any) => {
        if (res.code == 200) {
          console.log('统一接口注册成功', res);
          userInfo.username = studentNo;
          userInfo.password = '123';
          console.log('统一请求接口数据监测', userInfo);
          handleCheck();
        }
      });
    }
    console.log('获取url', currentUrl.value, studentNo, studentName);
  });
  const router = useRouter();
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();

  const loginConfig = useStorage('login-config', {
    rememberPassword: false,
    username: '',
    password: '',
  });

  const userInfo = reactive({
    username: loginConfig.value.username,
    password: loginConfig.value.password,
  });

  const loginRules = {
    username: [
      {
        required: true,
        message: '请输入用户名',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
      },
    ],
  };
  // 密码写死，跳转本页面的时候 进行获取url 参数 获取到用户名去注册，注册完成，再调用登录密码123
  const loginForm = ref();
  const handleCheck = () => {
    // 下面真正登录代码;

    if (loading.value) return;
    loginForm.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          setLoading(true);
          try {
            await userStore.login(userInfo);
            const { redirect, ...othersQuery } =
              router.currentRoute.value.query;
            router.push({
              name: (redirect as string) || 'dashboard',
              query: {
                ...othersQuery,
              },
            });
            // 实际生产环境需要进行加密存储。
            // loginConfig.value.username = loginConfig.value
            //   ? userInfo.username
            //   : '';
            // loginConfig.value.password = loginConfig.value
            //   ? userInfo.password
            //   : '';
          } catch (err) {
            console.log(err);
          } finally {
            setLoading(false);
          }
        }
      }
    );
  };
  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };
</script>
<style>
  .djbox {
    width: 137px;
    height: 60px;
    background: rgba(0, 0, 0, 0.3);
    border-radius: 10px 10px 10px 10px;
    position: absolute;
    top: 50px;
    left: 50px;
    font-size: 28px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .login_gl {
    width: 750px;
    height: 534px;
    position: absolute;
    left: 0px;
    top: 0px;
  }
  .loginbott {
    width: 628px;
    height: 90px;
    background: linear-gradient(180deg, #95a2b0 0%, #5c6a7a 100%);
    border-radius: 10px 10px 10px 10px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32px;
  }
  .login_form .arco-form-item-wrapper-col {
    border-radius: 10px;
    overflow: hidden;
  }
  .login_container {
    background-color: #5c6a7a;
  }
  .jzmm .arco-checkbox-label {
    font-size: 25px !important;
  }
  .jzmm .arco-checkbox-icon {
    width: 20px;
    height: 20px;
  }
  .login_formcont .arco-icon {
    font-size: 40px;
    width: 40px;
    height: 40px;
  }
  .jzmm {
    margin-top: 5px;
    margin-bottom: 60px;
    font-size: 25px !important;
  }
</style>
